<?php

class Service extends \Eloquent {
	protected $fillable = [];


    public function customer(){
        return $this->belongsTo('Customer');
    }
    public function mount(){
        return $this->belongsTo('Mount');
    }

    public function work(){
        return $this->belongsTo('Work','worker_id','id');
    }
    public function rate(){
        return $this->belongsTo('Rate');
    }

    public function commodity(){
        return $this->belongsTo('Commodity','filters','id');
    }
    public function comments()
    {
        return $this->hasMany('Comment');
    }


    public static function insert_try($customer_id,$mount_id, $type, $state,$section_id,$remark,$city_id,$work_id = null,$biaozhun = null)
    {
        $service = new Service;
        $service->customer_id   = $customer_id;
        $service->mount_id   = $mount_id;
        $service->type   = $type;
        $service->section_id   = $section_id;
        $service->state   = $state;
        $service->remark   = $remark;
        $service->city_id   = $city_id;
        $service->worker_id   = $work_id;
        $service->biaozhun   = $biaozhun;
        $service->save();
        return $service->id;
    }

    public static function paidan($service_id,$work_id){
        $service = Service::find($service_id);
        $work = Work::find($work_id);
        if($service->section_id == 0){
            $service->section_id = $work->section_id;
            $mount = Mount::find($service->mount_id);
            $mount->section_id = $work->section_id;
            $mount->save();
        }

        $service->worker_id = $work_id;
        $service->state = 2;
        $service->save();
    }

    public static function newcreate($type,$mount_id){
        $mount = Mount::find($mount_id);
        if($mount->state == 1){
            $mount->state = 2;
            $mount->save();
            $service = new Service;
            $service->customer_id   = $mount->customer_id;
            $service->mount_id   = $mount_id;
            $service->type   = $type;
            $service->section_id   = $mount->section_id;
            $service->state   = 1;
            $service->save();
            return $service->id;
        }
    }

    public static function findservice($code){

        $filterins = Service::whereHas('mount', function($q) use ($code)
        {
            $q->where('code', $code);

        })->where('state',2)->first();

        return $filterins;
    }
    public static function findservices($worker_id){

        $filterins = Service::whereHas('mount', function($q) use ($worker_id)
        {
            $q->where('worker_id', $worker_id);

        })->where('state',2)->get();

        return $filterins;
    }
}